<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div class="app-container" v-loading="loading">
        <!-- 随访基础信息 -->
        <el-descriptions title="随访基础信息" direction="vertical" :column="3" border>
          <el-descriptions-item label="患者姓名">{{
            visitInfo.name
          }}</el-descriptions-item>
          <el-descriptions-item label="患者电话">{{
            visitInfo.phone
          }}</el-descriptions-item>
          <el-descriptions-item label="患者病情">{{
            visitInfo.subTitle
          }}</el-descriptions-item>
          <el-descriptions-item label="随访标题">{{
            visitInfo.visitTitle
          }}</el-descriptions-item>
          <el-descriptions-item label="随访轮次">{{
            "第" + visitInfo.visitCount + "轮"
          }}</el-descriptions-item>
          <el-descriptions-item label="随访状态">
            <dict-tag
              size="small"
              :options="dict.type.gonitis_visit_status"
              :value="visitInfo.visitStatus"
            />
          </el-descriptions-item>
        </el-descriptions>

        <!-- 随访阶段信息 -->
        <div class="step-container" v-loading="stepLoading">
          <h3 style="color: #00000; font-weight: bold">随访阶段信息</h3>
          <el-tabs
            @tab-click="handleClick"
            v-model="stepTabValue"
            @edit="handleStepTabs"
            type="card"
            editable
            v-if="stepList && stepList.length > 0"
          >
            <el-tab-pane
              :key="index"
              v-for="(item, index) in stepList"
              :label="'第 ' + item.visitStep + ' 阶段'"
              :name="index + ''"
            >
              <el-form
                :rules="dataRule"
                ref="stepFormData"
                :model="stepList[index]"
                label-width="80px"
              >
                <el-form-item label="随访标题" prop="stepTitle">
                  <el-input
                    v-model="stepList[index].stepTitle"
                    style="font-size: 14px; width: 78%"
                    :disabled="item.status === 2"
                    :maxlength="11"
                    show-word-limit
                    clearable
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>

                <el-form-item label="随访模块">
                  <el-cascader
                    style="width: 230px"
                    :props="defaultProps"
                    v-model="subModels"
                    @change="handleSubChange"
                    :options="deptOptions"
                  ></el-cascader>
                  <el-select v-model="moduleId" placeholder="请选择随访模块">
                    <el-option
                      style="width: 250px"
                      v-for="item in moduleOptions"
                      :key="item.id"
                      :label="item.moduleName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                  <el-button
                    @click="moduleClick"
                    icon="el-icon-plus"
                    style="margin-left: 30px"
                    type="primary"
                    size="small"
                    plain
                    >添加模块</el-button
                  >
                </el-form-item>
              </el-form>

              <el-card class="box-card" v-loading="cardLoading">
                <div slot="header" class="clearfix">
                  <span>已选模块</span>
                  <el-button
                    @click="clearAll"
                    style="float: right; padding: 3px 0"
                    type="text"
                    >清除所有</el-button
                  >
                </div>
                <el-table :data="stepList[index].moduleList" stripe style="width: 100%">
                  <el-table-column
                    align="center"
                    prop="id"
                    label="模块编号"
                    width="100"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="moduleName"
                    label="模块名称"
                    :show-overflow-tooltip="true"
                    width="150"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="moduleSort"
                    label="显示顺序"
                  ></el-table-column>
                  <el-table-column prop="fieldType" align="center" label="操作">
                    <template slot-scope="scope">
                      <el-popover placement="bottom" width="600" trigger="click">
                        <el-descriptions
                          class="margin-top"
                          title="随访模块信息"
                          :column="3"
                          border
                        >
                          <el-descriptions-item>
                            <template slot="label">模块名称</template>
                            {{ detailModule.moduleName }}
                          </el-descriptions-item>
                          <el-descriptions-item>
                            <template slot="label">患者来源</template>
                            {{ detailModule.subName }}
                          </el-descriptions-item>
                          <el-descriptions-item>
                            <template slot="label">模块备注</template>
                            {{ detailModule.remark }}
                          </el-descriptions-item>
                        </el-descriptions>
                        <h3 style="color: #00000; font-weight: bold">模块字段信息</h3>
                        <el-table :data="detailFileds" stripe style="width: 100%">
                          <el-table-column
                            prop="id"
                            label="字段编号"
                            align="center"
                            width="100"
                          />
                          <el-table-column
                            prop="fieldName"
                            align="center"
                            label="字段名称"
                            width="100"
                            :show-overflow-tooltip="true"
                          />
                          <el-table-column
                            prop="fieldSort"
                            align="center"
                            label="字段顺序"
                          />
                          <el-table-column
                            prop="fieldType"
                            align="center"
                            label="字段类型"
                          >
                            <template slot-scope="scope">{{
                              scope.row.fieldType === 0 ? "文本" : "数字"
                            }}</template>
                          </el-table-column>
                          <el-table-column
                            prop="fieldValue"
                            align="center"
                            label="回复内容"
                            :show-overflow-tooltip="true"
                          >
                            <template slot-scope="scope">{{
                              getFieldValue(scope.row)
                            }}</template>
                          </el-table-column>
                        </el-table>
                        <el-button
                          type="text"
                          size="mini"
                          icon="el-icon-view"
                          slot="reference"
                          style="margin-right: 3px"
                          v-model="moduleVisible"
                          @click="moduleInfo(scope.row.id)"
                          >查看</el-button
                        >
                      </el-popover>
                      <el-button
                        type="text"
                        size="mini"
                        icon="el-icon-delete"
                        @click="deleteModuleHandle(scope.row.id)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>

              <div style="margin-top: 30px">
                <div class="text-item">
                  <span>创建时间：</span>
                  <span>{{ item.createTime }}</span>
                </div>

                <div class="text-item">
                  <span>完成状态：</span>
                  <span>
                    <dict-tag
                      :options="dict.type.visit_step_status"
                      :value="item.status"
                    />
                  </span>
                </div>
              </div>
              <div>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="此按钮只能完善当前阶段信息"
                  placement="top"
                >
                  <el-button
                    icon="el-icon-s-claim"
                    v-if="!item.replyContent"
                    type="primary"
                    @click="updateStep(index)"
                    size="small"
                    >{{ submitTitle }}</el-button
                  >
                </el-tooltip>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <hr style="margin-top: 20px" />
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="handleClose">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加随访阶段"
      :visible.sync="addStepVisible"
      width="30%"
      :before-close="addStepClose"
    >
      <el-form :model="addStepForm" ref="addStepData" :rules="addRule" label-width="80px">
        <el-form-item label="阶段标题" prop="stepTitle">
          <el-input
            v-model="addStepForm.stepTitle"
            :maxlength="18"
            show-word-limit
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addStepClose">取 消</el-button>
        <el-button type="primary" @click="subStepForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  detailVisit,
  moduleList,
  detailVisitModule,
  updateStep,
  removeStep,
  saveStep,
} from "@/api/gonitis/visit";
import { subTree } from "@/api/gonitis/illSub";
export default {
  name: "EditStep",
  dicts: ["gonitis_visit_status", "visit_step_status"],
  data() {
    //这里存放数据
    return {
      addStepForm: {
        stepTitle: "",
      },
      addStepVisible: false,
      moduleFlag: undefined,
      // 模块详情
      detailModule: {
        moduleName: "",
        subName: "",
        remark: "",
      },
      // 字段信息
      detailFileds: [],
      // 模块是否可见
      moduleVisible: false,
      submitTitle: "",
      cardLoading: false,
      stepLoading: false,
      // 模块绑定值
      moduleId: undefined,
      // 病情集合绑定值
      subModels: [],
      // 病情多选框映射
      defaultProps: {
        children: "children",
        label: "label",
        value: "id",
      },
      // 模块分类
      moduleOptions: [],
      // 疾病分类
      deptOptions: [],
      // tab绑定值
      stepTabValue: undefined,
      // 随访标题
      title: undefined,
      // 随访基础信息
      visitInfo: {
        id: undefined,
        visitTitle: undefined,
        visitCount: undefined,
        visitStatus: undefined,
        subTitle: undefined,
        phone: undefined,
        name: undefined,
      },
      loading: false,
      // step集合
      stepList: [],
      editableTabsValue: "",
      dialogVisible: false,
      dataRule: {
        stepTitle: [
          {
            validator: (rule, value, callback) => {
              if (!this.stepList[this.stepTabValue].stepTitle) {
                callback(new Error("随访标题必须填写"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: "blur",
          },
        ],
        moduleId: [],
      },
      addRule: {
        stepTitle: [{ message: "随访标题必须填写", required: true, trigger: "blur" }],
      },
    };
  },

  //方法集合
  methods: {
    getFieldValue(row) {
      const type = row.fieldType;
      const value = row.fieldValue;
      if (this.stepList[this.stepTabValue].status !== 2) {
        return "未回复";
      } else if (type === 0) {
        return value;
      } else {
        return value !== "暂无" ? value + "【级】" : value;
      }
    },
    /** 提交随访表单 */
    subStepForm() {
      this.$refs["addStepData"].validate((valid) => {
        if (!valid) return;
        // 获取当前stepList的长度
        this.cardLoading = true;
        const data = {
          stepTitle: this.addStepForm.stepTitle,
          visitId: this.visitInfo.id,
        };
        saveStep(data)
          .then((response) => {
            this.$modal.msgSuccess("添加成功");
            const stepInfo = response.data;
            stepInfo.status = 0;
            this.stepList.push(stepInfo);
          })
          .catch(() => {})
          .finally(() => {
            this.cardLoading = false;
            this.addStepVisible = false;
            this.addStepForm.stepTitle = "";
          });
      });
    },
    /** 关闭对话框 */
    addStepClose() {
      this.addStepVisible = false;
    },
    /** 清空所有模块信息 */
    clearAll() {
      const stepTabValue = this.stepTabValue;
      this.stepList[stepTabValue].moduleList = [];
      this.stepList[stepTabValue].moduleIds = "";
      this.detailFileds = [];
      this.resetDetailModule();
    },
    // 判断是否包含索引Id
    hasIndexId(str, id) {
      str += "";
      id += "";
      const arr = str.split("/");
      if (arr.indexOf(id) !== -1) {
        return true;
      }
      return false;
    },
    /** 删除模块 */
    deleteModuleHandle(idToRemove) {
      const stepTabValue = this.stepTabValue;
      this.stepList[stepTabValue].moduleList = this.stepList[
        stepTabValue
      ].moduleList.filter((item) => item.id !== idToRemove);
      this.resetDetailModule();
      this.detailFileds = [];
      const str = this.stepList[stepTabValue].moduleIds + "";
      const id = idToRemove + "";
      const arr = str.split("/");
      const indexToRemove = arr.indexOf(id);
      if (indexToRemove !== -1) {
        arr.splice(indexToRemove, 1);
      }
      const newStr = arr.join("/");
      this.stepList[stepTabValue].moduleIds = newStr;
      this.stepList[stepTabValue].moduleIds = newStr;
    },
    /** 查看模块详情 */
    moduleInfo(id) {
      const stepId = this.stepList[this.stepTabValue].id;
      const query = {
        moduleId: id,
        stepId: stepId,
      };
      detailVisitModule(query).then((response) => {
        const data = response.data;
        this.detailFileds = data.params.fieldList;
        data.params = null;
        this.detailModule = data;
        this.moduleVisible = true;
      });
    },
    /** 添加模块 */
    moduleClick() {
      const stepTabValue = this.stepTabValue;
      if (!this.moduleId) {
        return;
      } else {
        this.cardLoading = true;
        const flag =
          !this.stepList[stepTabValue].moduleIds ||
          this.stepList[stepTabValue].moduleIds.length === 0;
        if (!flag) {
          if (this.hasIndexId(this.stepList[stepTabValue].moduleIds, this.moduleId)) {
            this.$message({
              message: "该模块信息已经添加",
              type: "warning",
            });
            this.moduleId = undefined;
            this.cardLoading = false;
            return;
          }
        }
        let moduleItem = null;
        const moduleOptions = this.moduleOptions;
        moduleOptions.forEach((item) => {
          if (item.id === this.moduleId) {
            moduleItem = item;
            return;
          }
        });
        if (moduleItem) {
          this.stepList[stepTabValue].moduleList =
            this.stepList[stepTabValue].moduleList || [];
          this.stepList[stepTabValue].moduleList.push(moduleItem);
          if (flag) {
            this.stepList[stepTabValue].moduleIds += this.moduleId;
          } else {
            this.stepList[stepTabValue].moduleIds += "/" + this.moduleId;
          }
          this.moduleId = undefined;
        }
        this.cardLoading = false;
      }
    },
    /** 病情分类选择框改变 */
    handleSubChange(value) {
      const subId = value[value.length - 1];
      // 发送请求查询对应病情的病人
      moduleList(subId).then((response) => {
        this.moduleOptions = response.data;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      subTree().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 编辑随访阶段信息 */
    handleStepTabs(targetName, action) {
      if (action === "remove") {
        // 删除
        this.removeStep(targetName);
      } else if (action === "add") {
        // 添加
        this.addStepVisible = true;
      }
    },
    /** 完善随访方法 */
    getData(id) {
      this.loading = true;
      detailVisit(id)
        .then((response) => {
          const visitInfo = response.data.visitInfo;
          const stepList = response.data.stepList;
          this.visitInfo = visitInfo.params.patientInfo;
          this.visitInfo.visitTitle = visitInfo.visitTitle;
          this.visitInfo.visitCount = visitInfo.visitCount;
          this.visitInfo.visitStatus = visitInfo.visitStatus;
          this.visitInfo.id = visitInfo.id;
          this.stepList = stepList;
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 初始化 */
    init(id, flag) {
      if (flag === 0) {
        // 完善随访
        this.moduleFlag = 0;
        this.submitTitle = "完善阶段";
        this.title = "完善随访阶段";
        this.dialogVisible = true;
        this.getDeptTree();
        this.getData(id);
      } else if (flag === 1) {
        this.moduleFlag = 1;
        this.submitTitle = "修改阶段";
        this.title = "修改随访阶段";
        this.dialogVisible = true;
        this.getDeptTree();
        this.getData(id);
      }
    },
    // 删除
    removeStep(value) {
      const removeId = this.stepList[value].id;
      this.$modal
        .confirm('是否确认删除【随访阶段】编号为"' + removeId + '"的数据项？')
        .then(() => {
          this.cardLoading = true;
          return removeStep(removeId);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          let removeIndex = value;
          this.stepList.splice(removeIndex, 1);
          this.stepTabValue = 0 + "";
        })
        .catch(() => {})
        .finally(() => {
          this.cardLoading = false;
        });
    },
    /** 修改阶段信息 */
    updateStep(index) {
      // 发送请求修改数据
      const stepTabValue = this.stepTabValue;
      this.$refs["stepFormData"][index].validate((valid) => {
        if (!valid) return;
        // 判断是否绑定随访模块
        if (
          !this.stepList[stepTabValue].moduleIds ||
          this.stepList[stepTabValue].moduleIds.length <= 0
        ) {
          this.$message({
            message: "请至少绑定一个随访模块",
            type: "warning",
          });
          return;
        } else {
          // 完善随访
          this.stepList[stepTabValue].status = 1;
          const data = {
            id: this.stepList[stepTabValue].id,
            stepTitle: this.stepList[stepTabValue].stepTitle,
            status: this.stepList[stepTabValue].status,
            moduleIds: this.stepList[stepTabValue].moduleIds,
          };
          this.stepLoading = true;
          updateStep(data)
            .then((response) => {
              this.$modal.msgSuccess("操作成功");
            })
            .catch(() => {
              if (this.moduleFlag === 0) {
                // 完善随访
                this.stepList[stepTabValue].status = 0;
              }
            })
            .finally(() => {
              this.stepLoading = false;
            });
        }
      });
    },
    /** 点击标签页触发事件 */

    handleClick(tab) {
      this.moduleId = "";
      this.subModels = [];
    },
    /** 关闭对话框 */

    handleClose() {
      this.stepList = [];
      this.dialogVisible = false;
      this.moduleVisible = false;
      this.detailFileds = [];
      this.resetDetailModule();
      this.moduleIds = [];
      this.moduleOptions = [];
      this.stepTabValue = 0 + "";
      this.subModels = [];
      this.loading = false;
      this.title = "";
      this.$emit("getDataList");
    },
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
    },
    /** 重新设置随访详情信息 */
    resetDetailModule() {
      this.detailModule.moduleName = "";
      this.detailModule.subName = "";
      this.detailModule.remark = "";
    },
  },
};
</script>
<style scoped>
.text-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-bottom: 10px;
}
.text-name {
  font-weight: bold;
  color: rgb(124, 120, 120);
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 530px;
}
</style>
